package cn.bigcontainer.alt.common.entity;

import cn.bigcontainer.alt.common.util.WoKit;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BigMap<K, V> extends HashMap<K,V> {

    public String getString (K key) {
        return getString (key, null);
    }

    public String getString (K key, String defaultValue) {
        V val = this.get(key);
        if (val == null || "".equals(val)) {
            return defaultValue;
        }
        return val.toString();
    }

    public Integer getInt (K key) {
        return WoKit.getInt(this.get(key));
    }

    public Integer getInt (K key, Integer defaultVal) {
        return WoKit.getInt(this.get(key), defaultVal);
    }

    public Boolean isEmpty (K key) {
    	return WoKit.isEmpty(this.get(key));
    }
    
    public BigMap<K, V> bigPut (K key, V value) {
        put(key, value);
        return this;
    }
    
    /**
     * @param key
     * @param value
     * @return
     */
    public Boolean bigEquals (K key, V value) {
        V v = get(key);
        if (v == null) {
        	return false;
        }
        return v.equals(value);
    }

    public BigMap<K, V> bigPutByPrefix (String prefix, V value) {
        for (K k : this.keySet()) {
            if (k.toString().endsWith(prefix)) {
                put(k, value);
            }
        }
        return this;
    }

    public BigMap<K, V> bigPutAll (Map<K,V> map) {
        putAll(map);
        return this;
    }

    public Long getLong (K key) {
        return WoKit.getLong(this.get(key));
    }

    public Long getLong (K key, Long defaultVal) {
        return WoKit.getLong(this.get(key), defaultVal);
    }

    public Boolean getBoolean (K key, Boolean defaultVal) {
        return WoKit.getBoolean(this.get(key), defaultVal);
    }

    public String[] getStrings (K key) {
        String val = getString(key);
        return val.split(",");
    }
    
    public List<String> getStringList (K key) {
        String val = getString(key);
        if (WoKit.isEmpty(val)) {
        	return new ArrayList<String>();
        }
        return Arrays.asList(val.split(","));
    }

    public String getStringBySuffix (String suffix) {
        for (K key : this.keySet()) {
            if (key.toString().endsWith(suffix)) {
                return getString(key);
            }
        }
        return null;
    }

    public String getStringByPrefix (String prefix) {
        for (K key : this.keySet()) {
            if (key.toString().startsWith(prefix)) {
                return getString(key);
            }
        }
        return null;
    }

    public List getList (K key) {
        return (List)get(key);
    }

    public void addToList (K key, Object obj) {
        List list = (List)get(key);
        if (list == null) {
            list = new ArrayList();
            super.put(key, (V)list);
        }
        list.add(obj);
    }
}
